package com.qg.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.qg.pojo.QgUser;
import com.qg.service.LoginQgUserService;
import com.qg.service.QgUserService;
import com.qg.utils.Constants;
import com.qg.utils.EmptyUtils;
import com.qg.utils.MD5;
import com.qg.utils.RedisUtil;
import com.qg.vo.QgUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class LoginQgUserServiceImpl implements LoginQgUserService {
    @Reference
    private QgUserService qgUserService;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public QgUserVo loginUser(String phone, String password) throws Exception {
        QgUser qgUser=qgUserService.LoginUser(phone,password);
        if(EmptyUtils.isEmpty(qgUser)){
            return null;
        }
        QgUserVo qgUserVo=new QgUserVo();
        String key=redisUtil.getStr(qgUser.getId());
        if(EmptyUtils.isEmpty(key)){
            key= MD5.getMd5(qgUser.getId(),16);
            String userJson= JSON.toJSONString(qgUser);
            redisUtil.setStr(Constants.token+key,userJson,Constants.timeOut);
        }
        BeanUtils.copyProperties(qgUser,qgUserVo);
        qgUserVo.setToken(key);
        return qgUserVo;
    }

    @Override
    public void userOut(String token) throws Exception {
        redisUtil.del(token);
    }
}
